/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 BFS
 * @param {TreeNode} root
 * @return {number}
 */
export var findBottomLeftValue = function (root) {
  const queue = [root]
  let ans = root.val
  while (queue.length > 0) {
    const sz = queue.length
    let leftTemp = queue[0]?.val
    for (let i = 0; i < sz; i++) {
      const node = queue.shift()
      if (node.left) queue.push(node.left)
      if (node.right) queue.push(node.right)
    }
    if (leftTemp !== null) ans = leftTemp
  }
  return ans
}

/**
 DFS
 * @param {TreeNode} root
 * @return {number}
 */
export var findBottomLeftValue2 = function (root) {
  let curlevel = 0
  let ans = root.val
  function dfs(node, level = 0) {
    if (!node) return
    level++
    dfs(node.left, level)
    dfs(node.right, level)
    if (level > curlevel) {
      curlevel = level
      ans = node.val
    }
  }
  dfs(root)
  return ans
}
